// 注入到页面的脚本
console.log('自动登录助手注入脚本已加载');

// 用于生成唯一请求ID
let requestCounter = 0;

const isLocalhost = window.location.hostname === 'localhost';
if (isLocalhost) {
  console.log('当前页面运行在localhost，禁用请求拦截与自动登录能力');
}

// 保存原始的fetch和XMLHttpRequest
const originalFetch = window.fetch;
const originalXMLHttpRequest = window.XMLHttpRequest;

// 追踪所有进行中的请求
const activeRequests = new Map();
const activeXHRRequests = new Map();

if (!isLocalhost) {
  // 拦截fetch请求
  window.fetch = function(...args) {
    const [url, options = {}] = args;
    
    const isSignIn = typeof url === 'string' && url.includes('/api/user/sign-in') && options.method === 'POST';
    const isSignOut = typeof url === 'string' && url.includes('/api/user/sign-out') && options.method === 'POST';

    // 创建一个可以被abort的controller
    const controller = new AbortController();
    const requestId = ++requestCounter;
    
    // 如果原始options中没有signal，添加我们的signal
    if (!options.signal) {
      options.signal = controller.signal;
    } else {
      // 如果已经有signal，需要合并信号
      const originalSignal = options.signal;
      const mergedController = new AbortController();
      
      // 监听原始信号
      originalSignal.addEventListener('abort', () => {
        mergedController.abort();
      });
      
      // 监听我们的信号
      controller.signal.addEventListener('abort', () => {
        mergedController.abort();
      });
      
      options.signal = mergedController.signal;
    }
    
    // 追踪请求，但排除登录和登出请求
    if (!isSignIn && !isSignOut) {
      activeRequests.set(requestId, controller);
    }

    // 执行原始fetch
    const fetchPromise = originalFetch.apply(this, args);
    
    // 请求完成后清理追踪
    fetchPromise.finally(() => {
      activeRequests.delete(requestId);
    });
    
    fetchPromise.then(response => {
      // 只有在请求成功时才执行后续逻辑
      if (!response.ok) {
        return;
      }
      
      // 拦截登出请求
      if (isSignOut) {
        console.log('拦截到成功的登出请求:', url);
        const currentDomain = window.location.hostname;
        
        // 通知content script记录登出时间
        window.postMessage({
          action: 'signOutDetected',
          domain: currentDomain,
          url: url
        }, '*');
      }
      
      // 拦截登录请求
      if (isSignIn) {
        console.log('拦截到成功的fetch登录请求:', url, options);
        
        // 记录最近的登录时间，用于避免立即切换账号
        window.lastManualLoginTime = Date.now();
        
        if (options.body) {
          try {
            const loginData = typeof options.body === 'string' ? 
              JSON.parse(options.body) : options.body;
            
            // 验证登录数据完整性
            const loginId = loginData.loginId || loginData.username || loginData.email;
            const password = loginData.password;
            const domain = loginData.domain || loginData.domId || window.location.hostname;
            
            if (loginId && password) {
              // 发送登录信息给content script
              window.postMessage({
                action: 'saveLoginInfo',
                loginId: loginId,
                password: password,
                domain: domain,
                hostname: window.location.hostname
              }, '*');
            } else {
              console.warn('登录数据不完整，跳过保存:', { loginId, password, domain });
            }
            
          } catch (e) {
            console.error('解析登录数据失败:', e);
          }
        }
      }
    }).catch(err => {
      // 捕获 fetch 的网络错误等，防止 Promise 链中断
      console.log('Fetch 拦截器捕获到错误:', err);
    });
    
    // 立即返回原始的 Promise，不影响页面正常逻辑
    return fetchPromise;
  };

  // 拦截 XMLHttpRequest
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url, ...args) {
    this._url = url;
    this._method = method;
    return originalOpen.apply(this, [method, url, ...args]);
  };

  XMLHttpRequest.prototype.send = function(...args) {
    const requestId = ++requestCounter;
    const isSignIn = this._url && this._url.includes('/api/user/sign-in') && this._method === 'POST';
    const isSignOut = this._url && this._url.includes('/api/user/sign-out') && this._method === 'POST';
    
    // 追踪XMLHttpRequest，但排除登录和登出请求
    if (!isSignIn && !isSignOut) {
      activeXHRRequests.set(requestId, this);
      
      // 监听请求完成，清理追踪
      const cleanup = () => {
        activeXHRRequests.delete(requestId);
      };
      
      this.addEventListener('load', cleanup);
      this.addEventListener('error', cleanup);
      this.addEventListener('abort', cleanup);
      this.addEventListener('timeout', cleanup);
    }
    
    return originalSend.apply(this, args);
  };
}

// 提供abort所有请求的方法
function abortAllActiveRequests() {
  console.log(`正在取消 ${activeRequests.size} 个fetch请求和 ${activeXHRRequests.size} 个XHR请求`);
  
  // 取消所有fetch请求
  activeRequests.forEach((controller, requestId) => {
    try {
      controller.abort();
    } catch (error) {
      console.warn(`取消fetch请求 ${requestId} 失败:`, error);
    }
  });
  
  // 取消所有XMLHttpRequest请求
  activeXHRRequests.forEach((xhr, requestId) => {
    try {
      if (xhr.readyState !== XMLHttpRequest.DONE && xhr.readyState !== XMLHttpRequest.UNSENT) {
        xhr.abort();
      }
    } catch (error) {
      console.warn(`取消XHR请求 ${requestId} 失败:`, error);
    }
  });
  
  // 清空追踪列表
  activeRequests.clear();
  activeXHRRequests.clear();
  
  console.log('所有活跃请求已取消完成');
}

// 监听来自content script的消息
window.addEventListener('message', function(event) {
  if (event.source !== window) return;
  
  const message = event.data;
  if (!message || typeof message !== 'object') return;
  
  if (message.action === 'abortAllRequests') {
    console.log('收到取消所有请求的指令');
    console.log(`当前活跃请求数量: fetch(${activeRequests.size}), XHR(${activeXHRRequests.size})`);
    abortAllActiveRequests();
    
  } else if (message.action === 'getLoginFormData') {
    console.log('获取登录表单数据');
    
    // 尝试从页面中获取登录表单数据
    const loginForm = document.querySelector('form[action*="sign-in"], form[action*="login"], form#loginForm, form.login-form');
    if (loginForm) {
      const usernameInput = loginForm.querySelector('input[name*="username"], input[name*="loginId"], input[name*="email"], input[type="email"]');
      const passwordInput = loginForm.querySelector('input[type="password"]');
      
      if (usernameInput && passwordInput && usernameInput.value && passwordInput.value) {
        window.postMessage({
          action: 'saveLoginInfo',
          loginId: usernameInput.value,
          password: passwordInput.value,
          domain: window.location.hostname,
          hostname: window.location.hostname
        }, '*');
      } else {
        console.log('登录表单数据不完整，跳过保存');
      }
    }
    
  } else if (message.action === 'checkLoginStatus') {
    console.log('检查登录状态');
    
    const account = message.account;
    checkUserLoginStatus(account, message.originUrl);
    
  } else if (message.action === 'loginCheckSettings') {
    console.log('收到登录检查设置:', message.settings);
    
    // 执行登录状态检查
    performLoginStatusCheck(message.account, message.settings, message.originUrl);
    
  } else if (message.action === 'performAutoLogin') {
    if (isLocalhost) {
      console.log('localhost环境跳过自动登录流程');
      return;
    }
    console.log('执行自动登录:', message.account);
    
    // 首先检查当前域名是否在登出后的冷却时间内
    const currentDomain = window.location.hostname;
    const requestId = ++requestCounter;
    
    // 发送冷却时间检查请求给content script
    window.postMessage({
      action: 'checkSignOutCooldown',
      domain: currentDomain,
      requestId: requestId
    }, '*');
    
    // 保存自动登录的数据，等待冷却检查结果
    window.pendingAutoLogin = {
      account: message.account,
      originUrl: message.originUrl,
      requestId: requestId
    };
    
  } else if (message.action === 'signOutCooldownResult') {
    console.log('收到登出冷却检查结果:', message);
    
    // 检查是否有对应的待处理自动登录请求
    if (window.pendingAutoLogin && window.pendingAutoLogin.requestId === message.requestId) {
      const pendingLogin = window.pendingAutoLogin;
      delete window.pendingAutoLogin;
      
      if (message.isInCooldown) {
        console.log(`域名 ${message.domain} 登出后冷却时间内，跳过自动登录。剩余时间: ${message.remainingTime}秒`);
        
        // 通知content script跳过自动登录
        window.postMessage({
          action: 'autoLoginSkipped',
          reason: 'signout_cooldown',
          remainingTime: message.remainingTime,
          domain: message.domain
        }, '*');
        return;
      }
      
      // 不在冷却时间内，执行自动登录
      const account = pendingLogin.account;
      const originUrl = pendingLogin.originUrl;
      
      // 方法1：直接调用API
      fetch('/api/user/sign-in', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          domain: account.domain,
          loginId: account.loginId,
          password: account.password
        })
      })
      .then(res => res.json())
      .then(res => {
        if (res.uIdToken) {
          console.log('自动登录成功');
          
          // 通知content script记录登录状态
          window.postMessage({
            action: 'autoLoginSuccess',
            account: account,
            hostname: window.location.hostname,
            uIdToken: res.uIdToken
          }, '*');
          
          window.location.href = originUrl;
        } else {
          console.error('自动登录失败');
        }
      })
      .catch(error => {
        console.error('自动登录请求失败:', error);
      });
    }
  }
});

// 检查用户登录状态
function checkUserLoginStatus(account, originUrl) {
  console.log('开始检查登录状态');
  
  // 请求content script获取设置
  window.postMessage({
    action: 'getLoginCheckSettings',
    account,
    originUrl
  }, '*');
}

// 执行登录状态检查
function performLoginStatusCheck(account, settings, originUrl) {
  const customEndpoint = settings ? settings.customCheckEndpoint : null;
  const enableLoginCheck = settings ? settings.enableLoginCheck : true;
  
  // 如果禁用了登录检查，直接执行自动登录
  if (enableLoginCheck === false) {
    console.log('登录状态检查已禁用，直接执行自动登录');
    window.postMessage({
      action: 'loginStatusChecked',
      isLoggedIn: false,
      account: account
    }, '*');
    return;
  }
  // 方法1：通过常见的用户信息接口检查登录状态
  let checkEndpoints = [
    '/api/user/profile'
  ];
  
  // 如果有自定义接口，优先使用
  if (customEndpoint) {
    checkEndpoints.unshift(customEndpoint);
  }
  
  // 方法4：尝试调用用户信息接口
  let checkedCount = 0;
  const totalChecks = checkEndpoints.length;
  
  checkEndpoints.forEach(endpoint => {
    fetch(endpoint, {
      method: 'GET',
      credentials: 'include', // 包含cookies
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(response => {
      checkedCount++;
      
      if (response.ok && response.status === 200) {
        console.log('通过API检测到已登录，正在验证用户身份:', endpoint);
        
        response.json().then(profileData => {
          // 假设用户信息接口返回的数据中包含可识别用户的字段
          const loggedInUser = profileData.loginId || profileData.username || profileData.email || (profileData.data && profileData.data.loginId);
          
          if (loggedInUser && loggedInUser === account.loginId) {
            console.log(`已作为正确的用户 (${loggedInUser}) 登录。`);
            window.postMessage({
              action: 'loginStatusChecked',
              isLoggedIn: true,
              account: account,
              originUrl: originUrl
            }, '*');
          } else {
            // 检查是否刚刚有手动登录操作（3秒内）
            const currentTime = Date.now();
            const isRecentManualLogin = window.lastManualLoginTime && (currentTime - window.lastManualLoginTime) < 3000;
            
            if (isRecentManualLogin) {
              console.log(`检测到用户不匹配，但刚刚有手动登录操作 (${Math.round((currentTime - window.lastManualLoginTime) / 1000)}秒前)，跳过自动切换。当前用户: ${loggedInUser}, 目标用户: ${account.loginId}`);
              window.postMessage({
                action: 'loginStatusChecked',
                isLoggedIn: true, // 视为已登录，避免切换
                account: account,
                originUrl: originUrl
              }, '*');
            } else {
              console.log(`已登录用户 (${loggedInUser}) 与目标用户 (${account.loginId}) 不匹配，将执行切换。`);
              window.postMessage({
                action: 'loginStatusChecked',
                isLoggedIn: false, // 视为未登录，以触发自动登录
                account: account,
                originUrl: originUrl
              }, '*');
            }
          }
        }).catch(e => {
          console.error('解析用户信息失败，假定未登录:', e);
          // 解析失败时，也视为未登录
          window.postMessage({
            action: 'loginStatusChecked',
            isLoggedIn: false,
            account: account,
            originUrl: originUrl
          }, '*');
        });

      } else if (checkedCount === totalChecks) {
        // 所有接口都检查完了，判断为未登录
        console.log('所有检查完成，判断为未登录');
        window.postMessage({
          action: 'loginStatusChecked',
          isLoggedIn: false,
          account: account,
          originUrl: originUrl
        }, '*');
      }
    })
    .catch(error => {
      checkedCount++;
      console.log('登录状态检查失败:', endpoint, error);
      
      if (checkedCount === totalChecks) {
        // 所有接口都检查完了，判断为未登录
        console.log('所有检查完成，判断为未登录');
        window.postMessage({
          action: 'loginStatusChecked',
          isLoggedIn: false,
          account: account,
          originUrl: originUrl
        }, '*');
      }
    });
  });
}

// 通过DOM元素检查登录状态
function checkLoginStatusByDOM() {
  // 常见的已登录状态指示器
  const loggedInSelectors = [
    '[class*="user-avatar"]',
    '[class*="user-menu"]',
    '[class*="logout"]',
    '[class*="profile"]',
    '.user-info',
    '.user-panel',
    '#userMenu',
    '.header-user',
    '[data-testid*="user"]'
  ];
  
  // 常见的未登录状态指示器  
  const notLoggedInSelectors = [
    '[class*="login"]',
    '[class*="sign-in"]',
    'form[action*="login"]',
    'form[action*="sign-in"]',
    'input[type="password"]'
  ];
  
  // 检查是否有登录状态的元素
  const hasLoggedInElements = loggedInSelectors.some(selector => {
    return document.querySelector(selector) !== null;
  });
  
  // 检查是否有登录表单（表示未登录）
  const hasLoginForm = notLoggedInSelectors.some(selector => {
    return document.querySelector(selector) !== null;
  });
  
  if (hasLoggedInElements && !hasLoginForm) {
    return true;
  }
  
  return false;
}

// 通过本地存储检查登录状态
function checkLoginStatusByStorage() {
  // 常见的登录token存储键名
  const tokenKeys = [
    'token',
    'authToken',
    'accessToken',
    'jwt',
    'userToken',
    'sessionToken',
    'bearerToken',
    'auth_token',
    'access_token'
  ];
  
  // 检查localStorage
  for (const key of tokenKeys) {
    if (localStorage.getItem(key)) {
      return true;
    }
  }
  
  // 检查sessionStorage
  for (const key of tokenKeys) {
    if (sessionStorage.getItem(key)) {
      return true;
    }
  }
  
  // 检查cookie中的登录信息
  const cookies = document.cookie.split(';');
  for (const cookie of cookies) {
    const [name] = cookie.trim().split('=');
    if (tokenKeys.some(key => name.toLowerCase().includes(key.toLowerCase()))) {
      return true;
    }
  }
  
  return false;
}

console.log('注入脚本初始化完成'); 
